"""
Cookie管理模块 - 处理抖音和快手Cookie的保存、读取和更新
"""

import os
import json
from typing import Dict, Optional


class CookieManager:
    """Cookie管理器"""
    
    def __init__(self, cookie_dir="cookies"):
        """初始化Cookie管理器

        Args:
            cookie_dir: Cookie文件存储目录
        """
        self.cookie_dir = cookie_dir
        self.douyin_cookie_file = os.path.join(cookie_dir, "douyin_cookies.txt")
        self.kuaishou_cookie_file = os.path.join(cookie_dir, "kuaishou_cookies.txt")
        self.bilibili_cookie_file = os.path.join(cookie_dir, "bilibili_cookies.txt")

        # 确保Cookie目录存在
        if not os.path.exists(cookie_dir):
            os.makedirs(cookie_dir)
    
    def save_douyin_cookies(self, cookies: Dict[str, str]) -> bool:
        """保存抖音Cookie到文件

        Args:
            cookies: Cookie字典

        Returns:
            bool: 保存是否成功
        """
        try:
            # 将Cookie字典转换回字符串格式保存
            cookie_string = "; ".join([f"{key}={value}" for key, value in cookies.items()])

            with open(self.douyin_cookie_file, 'w', encoding='utf-8') as f:
                f.write(cookie_string)

            return True
        except Exception:
            return False
    
    def save_kuaishou_cookies(self, cookies: Dict[str, str]) -> bool:
        """保存快手Cookie到文件

        Args:
            cookies: Cookie字典

        Returns:
            bool: 保存是否成功
        """
        try:
            # 将Cookie字典转换回字符串格式保存
            cookie_string = "; ".join([f"{key}={value}" for key, value in cookies.items()])

            with open(self.kuaishou_cookie_file, 'w', encoding='utf-8') as f:
                f.write(cookie_string)

            return True
        except Exception:
            return False

    def save_bilibili_cookies(self, cookies: Dict[str, str]) -> bool:
        """保存B站Cookie到文件

        Args:
            cookies: Cookie字典

        Returns:
            bool: 保存是否成功
        """
        try:
            # 将Cookie字典转换回字符串格式保存
            cookie_string = "; ".join([f"{key}={value}" for key, value in cookies.items()])

            with open(self.bilibili_cookie_file, 'w', encoding='utf-8') as f:
                f.write(cookie_string)

            return True
        except Exception:
            return False

    def load_douyin_cookies(self) -> Optional[Dict[str, str]]:
        """从文件加载抖音Cookie

        Returns:
            Optional[Dict[str, str]]: Cookie字典，如果加载失败返回None
        """
        try:
            if not os.path.exists(self.douyin_cookie_file):
                return None

            with open(self.douyin_cookie_file, 'r', encoding='utf-8') as f:
                cookie_string = f.read().strip()

            # 如果文件内容是JSON格式（兼容旧版本）
            if cookie_string.startswith('{'):
                try:
                    cookie_data = json.loads(cookie_string)
                    return cookie_data.get("cookies", {})
                except:
                    pass

            # 解析Cookie字符串格式
            return self.parse_cookie_string(cookie_string)

        except Exception:
            return None
    
    def load_kuaishou_cookies(self) -> Optional[Dict[str, str]]:
        """从文件加载快手Cookie

        Returns:
            Optional[Dict[str, str]]: Cookie字典，如果加载失败返回None
        """
        try:
            if not os.path.exists(self.kuaishou_cookie_file):
                return None

            with open(self.kuaishou_cookie_file, 'r', encoding='utf-8') as f:
                cookie_string = f.read().strip()

            # 如果文件内容是JSON格式（兼容旧版本）
            if cookie_string.startswith('{'):
                try:
                    cookie_data = json.loads(cookie_string)
                    return cookie_data.get("cookies", {})
                except:
                    pass

            # 解析Cookie字符串格式
            return self.parse_cookie_string(cookie_string)

        except Exception:
            return None

    def load_bilibili_cookies(self) -> Optional[Dict[str, str]]:
        """从文件加载B站Cookie

        Returns:
            Optional[Dict[str, str]]: Cookie字典，如果加载失败返回None
        """
        try:
            if not os.path.exists(self.bilibili_cookie_file):
                return None

            with open(self.bilibili_cookie_file, 'r', encoding='utf-8') as f:
                cookie_string = f.read().strip()

            # 如果文件内容是JSON格式（兼容旧版本）
            if cookie_string.startswith('{'):
                try:
                    cookie_data = json.loads(cookie_string)
                    return cookie_data.get("cookies", {})
                except:
                    pass

            # 解析Cookie字符串格式
            return self.parse_cookie_string(cookie_string)

        except Exception:
            return None

    def parse_cookie_string(self, cookie_string: str) -> Dict[str, str]:
        """解析Cookie字符串为字典
        
        Args:
            cookie_string: Cookie字符串
            
        Returns:
            Dict[str, str]: 解析后的Cookie字典
        """
        cookies_dict = {}
        
        # 处理多种Cookie格式
        cookie_string = cookie_string.strip()
        
        # 如果包含换行符，按行分割
        if '\n' in cookie_string:
            lines = cookie_string.split('\n')
            for line in lines:
                line = line.strip()
                if '=' in line and not line.startswith('#'):
                    self._parse_single_cookie_line(line, cookies_dict)
        else:
            # 单行Cookie，按分号分割
            if ';' in cookie_string:
                parts = cookie_string.split(';')
                for part in parts:
                    part = part.strip()
                    if '=' in part:
                        self._parse_single_cookie_line(part, cookies_dict)
            else:
                # 单个Cookie
                if '=' in cookie_string:
                    self._parse_single_cookie_line(cookie_string, cookies_dict)
        
        return cookies_dict
    
    def _parse_single_cookie_line(self, line: str, cookies_dict: Dict[str, str]):
        """解析单行Cookie
        
        Args:
            line: Cookie行
            cookies_dict: 要更新的Cookie字典
        """
        try:
            # 找到第一个等号的位置
            eq_pos = line.find('=')
            if eq_pos > 0:
                key = line[:eq_pos].strip()
                value = line[eq_pos + 1:].strip()
                
                # 移除可能的引号
                if value.startswith('"') and value.endswith('"'):
                    value = value[1:-1]
                elif value.startswith("'") and value.endswith("'"):
                    value = value[1:-1]
                
                cookies_dict[key] = value
        except Exception:
            pass  # 忽略解析失败的行
    
    def update_douyin_cookies(self, new_cookies: Dict[str, str]) -> bool:
        """更新抖音Cookie（合并新旧Cookie）
        
        Args:
            new_cookies: 新的Cookie字典
            
        Returns:
            bool: 更新是否成功
        """
        try:
            # 加载现有Cookie
            existing_cookies = self.load_douyin_cookies() or {}
            
            # 合并Cookie
            existing_cookies.update(new_cookies)
            
            # 保存更新后的Cookie
            return self.save_douyin_cookies(existing_cookies)
        except Exception:
            return False
    
    def update_kuaishou_cookies(self, new_cookies: Dict[str, str]) -> bool:
        """更新快手Cookie（合并新旧Cookie）
        
        Args:
            new_cookies: 新的Cookie字典
            
        Returns:
            bool: 更新是否成功
        """
        try:
            # 加载现有Cookie
            existing_cookies = self.load_kuaishou_cookies() or {}
            
            # 合并Cookie
            existing_cookies.update(new_cookies)
            
            # 保存更新后的Cookie
            return self.save_kuaishou_cookies(existing_cookies)
        except Exception:
            return False

    def update_bilibili_cookies(self, new_cookies: Dict[str, str]) -> bool:
        """更新B站Cookie（合并新旧Cookie）

        Args:
            new_cookies: 新的Cookie字典

        Returns:
            bool: 更新是否成功
        """
        try:
            # 加载现有Cookie
            existing_cookies = self.load_bilibili_cookies() or {}

            # 合并Cookie
            existing_cookies.update(new_cookies)

            # 保存更新后的Cookie
            return self.save_bilibili_cookies(existing_cookies)
        except Exception:
            return False

    def get_cookie_info(self, platform: str) -> Optional[Dict]:
        """获取Cookie信息（包括时间戳）
        
        Args:
            platform: 平台名称 ("douyin" 或 "kuaishou")
            
        Returns:
            Optional[Dict]: Cookie信息，包含cookies和timestamp
        """
        try:
            if platform == "douyin":
                file_path = self.douyin_cookie_file
            elif platform == "kuaishou":
                file_path = self.kuaishou_cookie_file
            elif platform == "bilibili":
                file_path = self.bilibili_cookie_file
            else:
                return None
            
            if not os.path.exists(file_path):
                return None
            
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception:
            return None
